<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>周业绩生成简化版</title>
    <link rel="stylesheet" href="../layui/css/layui.css">
    <style>
        .input-section {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #e6e6e6;
            border-radius: 2px;
        }
        .input-section legend {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        textarea {
            min-height: 150px; /* Adjust height as needed */
            resize: vertical; /* Allow vertical resizing */
        }
    </style>
</head>
<body>

<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    <legend style="text-align: center">周业绩生成简化版</legend>
</fieldset>

<div class="layui-container" style="padding: 20px;">

    <div class="layui-row layui-col-space15">
        <!-- 下单数据区域 -->
        <div class="layui-col-md6">
            <div class="input-section">
                <legend>1. 粘贴下单数据</legend>
                <p class="layui-text">请从Excel复制下单数据的三列 (中类, 数量, 金额)，粘贴到下方文本框中。</p>
                <textarea id="orderDataInput" placeholder="在此处粘贴下单数据，每行一条记录，列之间用Tab分隔..." class="layui-textarea"></textarea>
                <button type="button" class="layui-btn" id="writeOrderDataBtn" style="margin-top: 10px;"><i class="layui-icon">&#xe609;</i> 写入下单数据</button>
            </div>
        </div>

        <!-- 发货数据区域 -->
        <div class="layui-col-md6">
            <div class="input-section">
                <legend>2. 粘贴发货数据</legend>
                <p class="layui-text">请从Excel复制发货数据的三列 (中类, 数量, 金额)，粘贴到下方文本框中。</p>
                <textarea id="shipmentDataInput" placeholder="在此处粘贴发货数据，每行一条记录，列之间用Tab分隔..." class="layui-textarea"></textarea>
                <button type="button" class="layui-btn" id="writeShipmentDataBtn" style="margin-top: 10px;"><i class="layui-icon">&#xe609;</i> 写入发货数据</button> 
             </div>
        </div>
    </div>

</div>

<script src="../layui/layui.js"></script>
<script>
    layui.use(['layer', 'jquery', 'form'], function(){
        var layer = layui.layer;
        var $ = layui.jquery;
        var form = layui.form; // 加载form模块

        // --- 配置 ---
        var API_BASE_URL = '/api/text-yeji'; // 后端API基础路径
        var errors = []; // Define errors array in a broader scope
        var hasForbiddenKeyword = false; // Flag for specific keyword
        var isOrderDataWritten = false; // 标志变量，跟踪下单数据是否已写入

        // --- 辅助函数 ---
        function validateAndPrepareData(textareaId) {
            var text = $('#' + textareaId).val().trim();
            errors = []; // Reset errors for each validation run
            hasForbiddenKeyword = false; // Reset flag

            if (!text) {
                layer.msg('输入框内容不能为空！', {icon: 2});
                return null;
            }

            var lines = text.split('\n');
            var dataToSend = [];

            for (var i = 0; i < lines.length; i++) {
                var line = lines[i].trim();
                if (!line) continue; // Skip empty lines

                // 1. Check for the specific forbidden keyword "空白"
                if (line.includes('空白')) {
                    hasForbiddenKeyword = true;
                    errors.push('第 ' + (i + 1) + ' 行: 包含不允许的关键字\'空白\'');
                    break; // Stop processing immediately
                }

                // 2. Split by Tab, expecting 3 columns
                var columns = line.split('\t');
                if (columns.length !== 3) {
                    errors.push('第 ' + (i + 1) + ' 行: 列数不为3 (应为 中类, 数量, 金额，使用Tab分隔)');
                    continue; // Skip this row
                }

                var zhonglei = columns[0].trim();
                var quantityStr = columns[1].trim();
                var amountStr = columns[2].trim();

                // 3. Check if required columns are empty after trimming
                if (!zhonglei) {
                    errors.push('第 ' + (i + 1) + ' 行: 中类不能为空');
                    continue;
                }
                if (quantityStr === '') {
                     errors.push('第 ' + (i + 1) + ' 行: 数量不能为空');
                     continue;
                }
                if (amountStr === '') {
                     errors.push('第 ' + (i + 1) + ' 行: 金额不能为空');
                     continue;
                }

                // 4. Check for valid numbers
                if (isNaN(parseFloat(quantityStr)) || !isFinite(quantityStr)) {
                     errors.push('第 ' + (i + 1) + ' 行: 数量 \'' + quantityStr + '\' 不是有效数字');
                     continue;
                }
                 if (isNaN(parseFloat(amountStr)) || !isFinite(amountStr)) {
                     errors.push('第 ' + (i + 1) + ' 行: 金额 \'' + amountStr + '\' 不是有效数字');
                     continue;
                }

                // If all checks pass for this line, add it
                dataToSend.push({
                    zhonglei: zhonglei,
                    quantity: quantityStr,
                    amount: amountStr
                });
            }

            // Prioritize reporting the forbidden keyword error
            if (hasForbiddenKeyword) {
                 layer.alert('输入数据校验失败：<br>' + errors.join('<br>'), {icon: 2, title: '输入错误'});
                 return null; // Halt processing
            }

            // Report other format/validation errors if found
            if (errors.length > 0) {
                 layer.alert('部分数据格式或内容有误，请检查（已跳过错误行）：<br>' + errors.join('<br>'), {icon: 2, title: '格式错误'});
                 // return null; // Uncomment to halt on any non-keyword error
            }

            // Check if any valid data remains after filtering errors
             if (dataToSend.length === 0) {
                 if (errors.length === 0) {
                    layer.msg('没有有效的可处理数据行！', {icon: 2});
                 }
                return null; // Halt if no valid data to send
            }

            return dataToSend;
        }

        function sendData(url, data, successCallback) {
            var loadingIndex = layer.load(1, { shade: [0.1, '#fff'] });

            $.ajax({
                url: API_BASE_URL + url,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(res){
                    layer.close(loadingIndex);
                    if(res && (res.code === 0 || res.success === true || (typeof res === 'string' && res.toLowerCase().includes('success')) ) ) { 
                         if(typeof successCallback === 'function') {
                            successCallback(res); 
                         } else {
                            layer.msg( (res && res.message) ? res.message : '操作成功！', {icon: 1});
                         }
                    } else {
                        layer.alert( (res && res.message) ? res.message : '操作失败，请稍后重试或联系管理员。', {icon: 2});
                    }
                },
                error: function(xhr, status, error){
                    layer.close(loadingIndex);
                    var errorMsg = '请求失败: ';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMsg += xhr.responseJSON.message;
                    } else if (xhr.responseText) {
                        try {
                            var errData = JSON.parse(xhr.responseText);
                            errorMsg += errData.message || errData.error || xhr.responseText;
                        } catch (e) {
                             errorMsg += xhr.responseText; 
                        }
                    } else if (error) {
                        errorMsg += error;
                    } else {
                        errorMsg += status;
                    }
                    layer.alert(errorMsg, {icon: 2});
                }
            });
        }

        // --- 事件绑定 ---

        $('#writeOrderDataBtn').on('click', function(){
            var data = validateAndPrepareData('orderDataInput');
            if (data && data.length > 0) { 
                var originalLineCount = $('#orderDataInput').val().trim().split('\n').filter(line => line.trim()).length;
                if (data.length < originalLineCount && errors.length > 0 && !hasForbiddenKeyword) { 
                     layer.confirm('部分数据行因格式错误已被忽略，是否继续写入剩余 ' + data.length + ' 条有效数据？', {icon: 3, title:'提示'}, function(index){
                         layer.close(index);
                         sendData('/write-orders', data, function(res){ 
                            layer.msg( (res && res.message) ? res.message : '下单数据写入成功！请继续粘贴发货数据。', {icon: 1});
                            isOrderDataWritten = true; // 更新标志
                         });
                     });
                 } else { 
                     sendData('/write-orders', data, function(res){ 
                         layer.msg( (res && res.message) ? res.message : '下单数据写入成功！请继续粘贴发货数据。', {icon: 1});
                         isOrderDataWritten = true; // 更新标志
                     });
                 } 
            } else if (data === null) {
                 // Validation halted, message already shown
            }
        });

        $('#writeShipmentDataBtn').on('click', function(){
            if (!isOrderDataWritten) {
                layer.msg('请先写入下单数据！', {icon: 2});
                return;
            }
            var data = validateAndPrepareData('shipmentDataInput');
            if (data && data.length > 0) {

                // --- Define the callback for successful YEJI GENERATION ---
                var generateYejiSuccessCallback = function(genRes) {
                     layer.confirm( (genRes && genRes.message) ? genRes.message : '周业绩数据已生成/更新。', { // Use message from generate endpoint
                         icon: 1,
                         title:'操作成功',
                         btn: ['下载周业绩Excel', '完成']
                     }, function(index){
                         // Trigger download
                         window.location.href = '/api/yeji/exportExcel';
                         layer.close(index); // Close confirm after clicking download
                     }, function(index){
                         layer.close(index);
                     });
                };

                // --- Define the callback for successful SHIPMENT WRITE ---
                var shipmentSuccessCallback = function(shipRes){
                     // Show initial success message for shipment write, then trigger generation
                     layer.msg( (shipRes && shipRes.message) ? shipRes.message : '发货数据写入成功！正在生成业绩...', {icon: 1, time: 2000}, function(){
                         // After shipment write is successful, call the generate endpoint
                         // Pass empty object {} as data for the POST request
                         sendData('/generate-yeji', {}, generateYejiSuccessCallback);
                     });
                };

                var originalLineCount = $('#shipmentDataInput').val().trim().split('\n').filter(line => line.trim()).length;
                if (data.length < originalLineCount && errors.length > 0 && !hasForbiddenKeyword) {
                     layer.confirm('部分数据行因格式错误已被忽略，是否继续写入剩余 ' + data.length + ' 条有效数据？', {icon: 3, title:'提示'}, function(index){
                         layer.close(index);
                         // Call sendData for shipment, using the shipmentSuccessCallback
                         sendData('/write-shipments', data, shipmentSuccessCallback);
                     });
                 } else {
                     // Call sendData for shipment, using the shipmentSuccessCallback
                     sendData('/write-shipments', data, shipmentSuccessCallback);
                 }
            } else if (data === null) {
                 // Validation halted, message already shown
            }
        });

    });
</script>

</body>
</html>